package com.zte.claa.inficombo.csa.app.service.redis;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zte.claa.inficombo.csa.app.model.dev.DevBase;
import com.zte.claa.inficombo.csa.app.model.dev.DevTpExtData;
import com.zte.claa.inficombo.csa.app.model.dev.DevTypeBase;
import com.zte.claa.inficombo.csa.app.model.dev.DevTypeModel;
import com.zte.claa.inficombo.csa.app.model.redis.DevMeteData;
import com.zte.claa.inficombo.csa.app.util.JsonUtils;

public class AicRecogChgListener extends DefaultMsgListener {
	private Logger logger = LoggerFactory.getLogger(AicRecogChgListener.class);
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public AicRecogChgListener(RedisMsgListenService listenService) {
		super(listenService);
	}

	@Override
	public void processMsgData(String jsonMsg) {
		try{
			JSONObject json = new JSONObject(jsonMsg);	
			logger.info("Aic recogition result:"+json.toString());
			String deveui = JsonUtils.getJsonAttrVal(json, "deveui", "");
			if(deveui.toUpperCase().equals("")){
				logger.error("Aic recogition result, deveui is null");
				return;
			}			
			String imageid = JsonUtils.getJsonAttrVal(json, "imageid", "");
			if(imageid.toUpperCase().equals("")){
				logger.error("Aic recogition result, imageid is null");
				return;
			}
			String resultcode = JsonUtils.getJsonAttrVal(json, "code", "ERROR");
			if(!resultcode.toUpperCase().equals("OK")){
				logger.error("Aic recogition result, code is not ok");				
			}
			
			String rpttimestr = JsonUtils.getJsonAttrVal(json, "reporttime", "");
			if(rpttimestr.toUpperCase().equals("")){
				logger.warn("Aic recogition result, rpttimestr is null");
				//return;
			}
			
			JSONObject dialobj = JsonUtils.getSubObject(json, "dialvalue");
			if (dialobj == null){  //Dereference null return value
				logger.warn("dialobj is null");
				return;
			}
			dialobj.put("photoid", imageid);
			dialobj.put("result", resultcode);
			DevBase devbase = this.listenService.getCacheManager().getDev(deveui);
			if(null == devbase){
				logger.warn("devbase is null");
				return;
			}
			this.parseMeteData(devbase, rpttimestr, dialobj.toString(),imageid);
		}catch(Exception e){
			logger.error("Aic recogition result " + e.getMessage(), e);
		}
	}
	
	private void parseMeteData(DevBase dev, String rpttime, String rptData, String photoid) throws Exception {
		String devTypeId = dev.getDevType();
		DevTypeModel dtm = this.listenService.getParserContainer().getCacheManager().getDevTypeModel(devTypeId);
		if(dtm == null || dtm.getDmList() == null || dtm.getBase() == null){
			logger.error("[*!!*]Can not get datamodel for devtype="+devTypeId);
			return;
		}
		Map<String, Object> mdata = JsonUtils.jsonStrToHashMap(rptData.toString());
		DevMeteData meteData = new DevMeteData();
		if(null!=rpttime && !"".equals(rpttime)){
			meteData.setRpttime(new Timestamp(sdf.parse(rpttime).getTime()));
		}
//		if((dtm.getBase().getFntype() & DevTpExtData.FN_TP_2) != 0){
//			mdata.put("msgtype", "AID图片识别");
//		}
		meteData.setAppeui(dev.getAppEui());
		meteData.setDeveui(dev.getDevEui());
		meteData.setDevname(dev.getDevName());
		meteData.setDevtype(devTypeId);
		meteData.setPort("0");
		meteData.setProjectid(dev.getProjectId());
		meteData.setMdata(mdata);	
		
		// 持久化数据.
		//this.listenService.getParserContainer().getPersisService().saveAicDevMeteData(meteData, dtm.getBase().getTbname(),photoid);
		this.listenService.getParserContainer().getPersisService().updateAicDevMeteData(meteData, dtm.getBase().getTbname(),photoid);
		// 5.构造广播数据，进行redis发布...
		String pubMsg = JsonUtils.toJson(meteData);
		this.listenService.getParserContainer().getUpdataPublisher().publishMessage(pubMsg);
		logger.info("[*^_^*]Publish metedata message ok: "+pubMsg);
	}
	
	
}
